__author__ = 'vivienfanghua'
import arcpy
import math
import random
import sys
from collections import Counter
if __name__=="__main__":
    if len(sys.argv)<5:
        print("Example: python testss.py FilePath PointNum NeighborSize IterTimes")
    shpFile = sys.argv[1]
    csvFile = shpFile + ".csv"
    MAXVALUE=10000000000.0
    iterTimes=int(sys.argv[4])
    pointSize=int(sys.argv[2])
    neighborSize=int(sys.argv[3])
    graph = [[MAXVALUE for j in range(pointSize)] for i in range(pointSize)]
    neighbors = [[] for i in range(pointSize)]
    sameNeighborNum=[0 for i in range(pointSize)]
    # sameNeighborRatio=[0 for i in range(pointSize)]
    type = []
    with open(csvFile) as f:
        for line in f.readlines():
            lineStrip=line.split(",")
            try:
                id1=int(lineStrip[0])
                id2=int(lineStrip[1])
                distance=float(lineStrip[2])
                graph[id1][id2]=distance
                graph[id2][id1]=distance
            except Exception as e:
                pass
    with arcpy.da.SearchCursor(shpFile, ("Type")) as cursor:
        try:
            for row in cursor:
                type.append(row[0])
        except Exception as e:
            pass
    for i in range(pointSize):
        sortDistances=sorted(graph[i])
        for j in range(neighborSize):
            neighbors[i].append(graph[i].index(sortDistances[j]))

    for i in range(pointSize):
        for j in range(neighborSize):
            if type[neighbors[i][j]]==type[i]:
                sameNeighborNum[i]+=1
    sameNeighborRatioCounter=Counter(sameNeighborNum)
    sameNeighborRatio=[(i,1.0*j/pointSize) for (i,j) in sameNeighborRatioCounter.items()]
    with open(shpFile+"-result.txt",'w') as out:
        for i in sameNeighborRatio:
            out.write("{}:{}\n".format(i[0],i[1]))
        out.close()
    h=0
    for item in sameNeighborRatio:
        if item[0]>0:h+=item[0]*math.log(item[0])

    with open(shpFile+"-h-random.txt",'w') as out:
        smallerTime=0
        for t in range(iterTimes):
            sameNeighborNum=[0 for i in range(pointSize)]
            random.shuffle(type)
            for i in range(pointSize):
                for j in range(neighborSize):
                    if type[neighbors[i][j]]==type[i]:
                        sameNeighborNum[i]+=1
            sameNeighborRatioCounter=Counter(sameNeighborNum)
            sameNeighborRatio=[(i,1.0*j/pointSize) for (i,j) in sameNeighborRatioCounter.items()]
            hrandom=0
            for item in sameNeighborRatio:
                if item[0]>0:hrandom+=item[0]*math.log(item[0])
            out.write(str(hrandom)+"\n")
            if hrandom<h:smallerTime+=1
        out.write("Ratio:{}".format(1.0*smallerTime/iterTimes))
        out.close()
# reduce(lambda x,y:x[0]*x[1]+y[0]+y[1],sameNeighborRatio,0)




